// pages/settings/index.js
const app = getApp();
const domain = app.globalData.domain
import {
  formatDate,
  formatDate2,
  formatDuration
} from '../../utils/date'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    clientList: [{
      label: '客户1',
      value: '客户1'
    }],
    clientSearchVal: null,
    clientShowAll: false,
    params: {},
    areaVis: false,
    currentArea: null,
    templateList: [],
    dtcTime: null
  },
  onAreaPick(e) {
    const {
      key
    } = e.currentTarget.dataset;
    const {
      value,
      label
    } = e.detail;

    console.log('picker change:', e, value);
    if (this.data.currentOp === 'select') {
      if (value?.[0])
        this.bindTemplateToArea(value?.[0])
    } else {
      if (value?.[0])
        this.changeTemplateArea(value?.[0])
    }
  },
  bindTemplateToArea(value) {
    const data = {
      ...this.data.data
    }

    // if (data.createTime) data.createTime = +new Date(data.createTime)
    console.log('', value, this.data.templateList)

    wx.request({
      url: `${domain}/admin-api/smc/scene-conf/create-instance-quick`,
      method: "POST",
      data: {
        sceneId: this.data.options.id,
        kind: 'instance',
        extendId: value,
        confNodes: []
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }

        if (res?.data?.code == 0) {
          wx.showToast({
            title: '绑定成功',
            icon: 'none'
          })
          this.initconf(res?.data?.data)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  sendToDtc(value) {
    const data = {
      ...this.data.data
    }

    // if (data.createTime) data.createTime = +new Date(data.createTime)
    console.log('this.data.options', this.data.options)
    wx.showLoading({
        title: '同步中',
      }),
      wx.request({
        timeout: 1000000,
        url: `${domain}/admin-api/smc/things/deploy-scene-conf?sceneId=${this.data.options.id}`,
        method: "POST",
        data: {
          sceneId: this.data.options.id,
          skipBuild: false,
        },
        header: {
          Authorization: wx.getStorageSync('token')
        },

        success: res => {
          wx.hideLoading()
          if (res?.data?.code == '401') {
            wx.removeStorageSync('token')
            wx.reLaunch({
              url: '../login/login',
            })
            return;
          }

          if (res?.data?.code == 0) {
            wx.showToast({
              title: '同步成功',
              icon: 'none'
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
          this.initconf(this.data.currentArea.id)
        },
        error() {
          wx.hideLoading()
        }
      })
  },


  changeTemplateArea(id) {
    // console.log('changeTemplateArea', id)
    wx.request({
      url: `${domain}/admin-api/smc/scene-conf/get?id=${id}`,
      data: {
        id
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        console.log('res', res)

        const resetData = {
          // ...res?.data.data,
          name: res?.data?.data?.name,
          confNodes: res?.data?.data?.confNodes,
          bussType: res?.data?.data?.bussType,
        }
        console.log('resetData', resetData)

        wx.request({
          url: `${domain}/admin-api/smc/scene-conf/update`,
          method: "PUT",
          data: {
            ...this.data.currentArea,
            ...resetData,
          },
          header: {
            Authorization: wx.getStorageSync('token')
          },
          success: res => {
            if (res?.data?.code == '401') {
              wx.removeStorageSync('token')
              wx.reLaunch({
                url: '../login/login',
              })
              return;
            }

            if (res?.data?.code == 0) {
              wx.showToast({
                title: '重置成功，可点击编辑进行操作',
                icon: 'none'
              })
              this.initconf(this.data.currentArea.id)
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          }
        })
      }
    })
    return
    const data = {
      ...this.data.data
    }

    // if (data.createTime) data.createTime = +new Date(data.createTime)
    console.log('', value, this.data.templateList)

    wx.request({
      url: `${domain}/admin-api/smc/scene-conf/create-instance-quick`,
      method: "POST",
      data: {
        sceneId: this.data.options.id,
        kind: 'instance',
        extendId: value,
        confNodes: []
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }

        if (res?.data?.code == 0) {
          wx.showToast({
            title: '绑定成功',
            icon: 'none'
          })
          this.initconf(res?.data?.data)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  setAreaVis(vis) {
    this.setData({
      areaVis: vis
    })
  },
  openAreaVis(e) {
    console.log('openAreaVis', e)

    const {
      op
    } = e.currentTarget.dataset
    this.setAreaVis(true)
    this.setData({
      currentOp: op
    })
  },
  onBack() {
    wx.redirectTo({
      url: '../operation/index',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  init(options) {
    wx.request({
      url: `${domain}/admin-api/smc/scene/get?id=${options.id}`,
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.error === "Unauthorized") {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        const params = res?.data?.data
        console.log('params', params)
        if (params.confId !== undefined) {
          // this.setData({
          //   currentArea: params.confId
          // })
          this.initconf(params.confId)
        }
        this.setData({
          params
        })
      }
    })
  },
  initTemplate(id) {
    wx.request({
      url: `${domain}/admin-api/smc/scene-conf/page`,
      data: {
        pageNum: 1,
        pageSize: 100,
        kind: 'config'
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        console.log('res', res)
        let data = res?.data?.data?.list

        data = data.map(item => {
          const obj = {
            label: item.name,
            value: item.id,
            item
          }
          return obj
        })
        this.setData({
          templateList: data
        })
      }
    })
  },
  initconf(id) {
    wx.request({
      url: `${domain}/admin-api/smc/scene-conf/get?id=${id}`,
      data: {},
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        // console.log('res', res)
        let data = res?.data?.data
        const dtcTime = formatDate(data?.downTime)
        // data = data.map(item => {
        //   const obj = {
        //     label: item.name,
        //     value: item.id
        //   }
        //   return obj
        // })
        this.setData({
          currentArea: data,
          dtcTime: data?.downTime ? formatDate(data?.downTime) : null
        })
      }
    })
  },
  onLoad(options) {
    console.log('options', options)
    this.setData({
      options
    })
    this.init(options)
    this.initTemplate()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.currentArea) {
      this.initconf(this.data.currentArea.id)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})